package com.hfp.mall.common.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BeanUtil {

    /**
     *
     * @param object
     * @param isCamel2Underline 是否需要转驼峰转下划线
     * @return
     */
    public static Map<String, Object> Bean2Map(Object object, boolean isCamel2Underline) {
        Map<String,Object> result=new HashMap<>();
        // 获得类的的属性名 数组
        Field[] fields=object.getClass().getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                String name = new String(field.getName());
                if(isCamel2Underline) {
                    result.put(camel2Underline(name), field.get(object));
                } else {
                    result.put(name, field.get(object));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 默认驼峰转下划线
     * @param object
     * @return
     */
    public static Map<String, Object> Bean2Map(Object object) {
        return Bean2Map(object, true);
    }
    /**
     * 驼峰法转下划线
     * @param line 源字符串
     * @return 转换后的字符串
     */
    public static String camel2Underline(String line) {
        if (line == null || "".equals(line)) {
            return "";
        }
        line = String.valueOf(line.charAt(0)).toUpperCase()
                .concat(line.substring(1));
        StringBuffer sb = new StringBuffer();
        Pattern pattern = Pattern.compile("[A-Z]([a-z\\d]+)?");
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end() == line.length() ? "" : "_");
        }
        return sb.toString();
    }
}
